<template>
  <div class="register-page">
    <div class="w1200">
      <a-tabs v-model="registerTabKey" :tabBarStyle="{ display: 'none' }">
        <a-tab-pane tab="" key="1">
          <div class="register-wrap">
            <img
              class="register-png"
              src="~assets/register/register.png"
              alt=""
            />
            <div class="register-form">
              <h2>注册</h2>
              <a-form-model
                ref="registerForm"
                :model="registerForm"
                :rules="rules"
              >
                <a-form-model-item prop="mobile">
                  <a-input
                    v-model="registerForm.mobile"
                    autocomplete="off"
                    placeholder="手机号"
                    @focus="clearValidate('registerForm', 'mobile')"
                  >
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconlogin_icon_account"></YxpIcon>
                        <span>账号</span>
                      </div>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="password">
                  <a-input
                    v-model="registerForm.password"
                    type="password"
                    autocomplete="off"
                    placeholder="密码(6至12位数字或字母)"
                    @focus="clearValidate('registerForm', 'password')"
                  >
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconlogin_icon_password"></YxpIcon>
                        <span>密码</span>
                      </div>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="repassword">
                  <a-input
                    v-model="registerForm.repassword"
                    type="password"
                    autocomplete="off"
                    placeholder="再次输入密码"
                    @focus="clearValidate('registerForm', 'repassword')"
                  >
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconlogin_icon_password"></YxpIcon>
                        <span>确认密码</span>
                      </div>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="shop_code">
                  <a-input
                    v-model="registerForm.shop_code"
                    @change="checkShop"
                    autocomplete="off"
                    placeholder="机构代码"
                    @focus="clearValidate('registerForm', 'shop_code')"
                  >
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconregister_icon_jigoudaima"></YxpIcon>
                        <span>机构代码</span>
                      </div>
                    </template>
                  </a-input>
                  <template v-if="shopError" slot="extra">
                    <span class="async-error">
                      {{ shopError }}
                    </span>
                  </template>
                </a-form-model-item>
                <a-form-model-item>
                  <a-input v-model="shopName" disabled autocomplete="off">
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconregister_icon_jigoudaima"></YxpIcon>
                        <span>机构名称</span>
                      </div>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="code">
                  <a-input
                    v-model="registerForm.code"
                    autocomplete="off"
                    placeholder="验证码"
                    @focus="clearValidate('registerForm', 'code')"
                  >
                    <template slot="prefix">
                      <div class="label-prefix">
                        <YxpIcon type="iconregister_icon_yanzhengma1"></YxpIcon>
                        <span>验证码</span>
                      </div>
                    </template>
                  </a-input>
                  <a-button
                    type="primary"
                    :disabled="disabled"
                    @click="getVerifyCode"
                    shape="round"
                    >{{ btnTitle }}</a-button
                  >
                </a-form-model-item>
                <a-form-model-item prop="read" label="">
                  <a-checkbox v-model="registerForm.read">
                      我已阅读并接受
                    <a @click="openUrl('/registration')"
                      >《用户注册协议》</a
                    ><a @click="openUrl('/privacyprotection')"
                      >《隐私权保护政策》</a
                    >
                  </a-checkbox>
                </a-form-model-item>
                <a-button
                  type="primary"
                  size="large"
                  block
                  shape="round"
                  @click="submitForm"
                  >下一步</a-button
                >
              </a-form-model>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane tab="" key="2">
          <div class="register-wrap step2-wrap">
            <img
              class="register-png"
              src="~assets/register/register2.png"
              alt=""
            />
            <div class="register-form">
              <h2>完善信息</h2>
              <a-form-model
                ref="personalForm"
                :model="personalForm"
                :rules="personalRules"
                :colon="false"
                :hideRequiredMark="true"
              >
                <a-form-model-item prop="name">
                  <a-input
                    v-model="personalForm.name"
                    autocomplete="off"
                    placeholder="真实姓名"
                    @focus="clearValidate('personalForm', 'name')"
                  >
                    <template slot="prefix">
                      <YxpIcon type="iconlogin_icon_account"></YxpIcon>
                      <span>姓名</span>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-form-model-item class="yxp-form-item" prop="sex">
                  <template slot="label">
                    <YxpIcon type="iconinformation_icon_sex"></YxpIcon>
                    <span>性别</span>
                  </template>
                  <label
                    class="yxp-radio-wrap"
                    :class="{ 'man-checked': personalForm.sex === '1' }"
                  >
                    <YxpIcon type="iconzu764"></YxpIcon>
                    <input
                      v-model="personalForm.sex"
                      name="sex"
                      value="1"
                      type="radio"
                    />男生
                  </label>
                  <label
                    class="yxp-radio-wrap"
                    :class="{ 'girl-checked': personalForm.sex === '2' }"
                  >
                    <YxpIcon type="iconzu767"></YxpIcon>
                    <input
                      v-model="personalForm.sex"
                      value="2"
                      name="sex"
                      type="radio"
                    />女生
                  </label>
                </a-form-model-item>
                <a-form-model-item class="yxp-form-item">
                  <template slot="label">
                    <YxpIcon type="iconinformation_icon_grade"></YxpIcon>
                    <span>年级</span>
                  </template>
                  <a-select
                    v-model="personalForm.grade"
                    placeholder="点击选择年级"
                  >
                    <a-select-option
                      v-for="item in gradeArr"
                      :value="item.grade"
                      :key="item.grade"
                    >
                      {{ item.grade_name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item prop="school" placeholder="在读学校名称">
                  <a-input
                    v-model="personalForm.school"
                    autocomplete="off"
                    placeholder="在读学校名称"
                    @focus="clearValidate('personalForm', 'school')"
                  >
                    <template slot="prefix">
                      <YxpIcon type="iconinformation_icon_school"></YxpIcon>
                      <span>学校</span>
                    </template>
                  </a-input>
                </a-form-model-item>
                <a-button
                  type="primary"
                  block
                  size="large"
                  shape="round"
                  @click="submitPersonal"
                  >完成</a-button
                >
              </a-form-model>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import {
  Modal,
  FormModel,
  Input,
  Checkbox,
  Tabs,
  Select,
  Radio
} from "ant-design-vue";
import {
  checkShopCode,
  fetchGrade,
  register,
  sendSms,
  setPersonal
} from "@/services";
import { validatePhone, validatePass } from "@/utils/form-validate";
import Footer from "@/components/layout/Footer";
import mTypes from "@/store/mutationsTypes";
import { mapMutations } from "vuex";
import {openBrowser} from '@/utils/tools'
import _ from "lodash";
export default {
  name: "register",
  components: {
    Footer,
    AModal: Modal,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ACheckbox: Checkbox,
    ASelect: Select,
    ASelectOption: Select.Option,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    ARadio: Radio,
    ARadioGroup: Radio.Group
  },
  data() {
    return {
      registerTabKey: this.$route.query.step || "1",
      btnTitle: "获取验证码",
      disabled: false,
      shopError: "",
      registerForm: {
        mobile: "",
        password: "",
        repassword: "",
        code: "",
        shop_code: "",
        read: true
      },
      personalForm: {
        name: "",
        sex: "1",
        grade: 1,
        school: ""
      },
      shopName: "",
      rules: {
        mobile: [{ validator: validatePhone, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        repassword: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请重新输入密码"));
              } else if (value !== this.registerForm.password) {
                callback(new Error("两次密码输入不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur"
          }
        ],
        read: [
          {
            required: true,
            message: "请确认勾选阅读协议"
          }
        ],
        shop_code: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入机构码"));
              } else if (value.length < 8) {
                callback(new Error("请输入8位机构码"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      personalRules: {
        name: [{ required: true, message: "此项不能为空", trigger: "blur" }],
        sex: [{ required: true, message: "此项不能为空", trigger: "blur" }],
        grade: [{ required: true, message: "此项不能为空", trigger: "blur" }],
        school: [{ required: true, message: "此项不能为空", trigger: "blur" }]
      },
      gradeArr: []
    };
  },
  computed: {},
  watch: {},
  methods: {
    ...mapMutations([mTypes.userInfo]),
    openUrl(remoteUrl) {
      const url = `/#${remoteUrl}`
      openBrowser(url)
    },
    validateBtn() {
      //倒计时
      let time = 60;
      this.disabled = true;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.disabled = false;
          this.btnTitle = "获取验证码";
        } else {
          this.btnTitle = time + "秒后重试";
          this.disabled = true;
          time--;
        }
      }, 1000);
    },
    getVerifyCode(e) {
      this.$refs.registerForm.validateField(["mobile"], async valid => {
        if (!valid) {
          this.validateBtn();
          let res = await sendSms({
            username: this.registerForm.mobile,
            type: 1
          });
          if (res.code === 1) {
            this.$message.success("验证码发送成功");
          }
        }
      });
    },
    checkShop(e) {
      console.log(e);
      if (e.target.value.length === 8) {
        checkShopCode({ shop_code: e.target.value }).then(res => {
          if (res.code === 1) {
            this.shopName = res.data.org_name;
            this.shopError = "";
          } else {
            this.shopName = "";
            this.shopError = "机构代码不正确";
          }
        });
      }
    },
    submitForm() {
      this.$refs.registerForm.validate(async valid => {
        if (valid) {
          let res = await register(_.omit(this.registerForm, "read"));
          if (res.code === 1) {
            this.$message.success("注册成功");
            this.registerTabKey = "2";
            this.$router.push({
              path: this.$route.path,
              query: { step: "2" }
            });
          } else if (res.code === 10029) {
            this.$router.push({
              path: "/"
            });
          }
        }
      });
    },
    submitPersonal() {
      this.$refs.personalForm.validate(async valid => {
        if (valid) {
          let res = await setPersonal({
            ...this.personalForm
          });
          if (res.code === 1) {
            this.$message.success("信息设置成功");
            // console.log(this[mTypes.userInfo], res.data)
            this[mTypes.userInfo](res.data);
            this.$router.push("/");
          }
        }
      });
    },
    clearValidate(form, filed) {
      this.$refs[form].clearValidate(filed);
    }
  },
  created() {
    fetchGrade().then(res => {
      if (res.code === 1) {
        this.gradeArr = res.data;
      }
    });
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  beforeRouteUpdate(to, from, next) {
    if (from.path === to.path) {
      this.registerTabKey = to.query.step || "1";
    }
    next();
  }
};
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */
.register-page {
  display: flex;
  flex-direction: column;
  background-image: url("~assets/register/register-bg.png");
  background-size: cover;
  min-height: calc(100vh - 70px);
  .label-prefix {
    width: 84px;
  }
  & /deep/ .ant-input-disabled {
    background-color: transparent;
    color: #000;
    font-weight: bold;
  }
  .register-wrap {
    display: flex;
    min-height: calc(100vh - 230px);
    align-items: center;
    justify-content: space-around;
    padding: 60px 0;
    margin: 50px 0 30px 0;
    height: 650px;
    background-color: #fff;
    box-shadow: 0px 0px 20px rgba(217, 224, 230, 0.5);
    border-radius: 20px; /* no */
    .register-png {
      width: 482px;
      height: 334px;
    }
  }

  .step2-wrap {
  }

  .register-form {
    width: 390px; /* no */

    /deep/ .ant-form-extra {
      & /deep/ .async-error {
        color: #ff4500;
      }
    }
  }
}

.yxp-form-item {
  display: flex;
  border-bottom: 1px solid #e0e0e0; /* no */
  & /deep/ .ant-form-item-control-wrapper {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex: 1;
  }
  /deep/ .ant-select-selection {
    border: none;
    display: flex;
    justify-content: center;
  }
  /deep/ .ant-select-focused .ant-select-selection,
  .ant-select-selection:focus,
  .ant-select-selection:active {
    box-shadow: none;
  }

  /deep/ .ant-select-arrow {
    position: relative;
    color: #000;
  }

  /deep/ .ant-form-item-no-colon {
    display: flex;
    align-items: center;
    color: rgba(0, 0, 0, 0.65);
    .anticon {
      margin-right: 6px; /* no */
    }
  }

  .yxp-radio-wrap {
    display: flex;
    align-items: center;
    &:nth-child(1) {
      margin-right: 30px;
    }
    &.man-checked {
      color: #5ca2ff;
    }
    &.girl-checked {
      color: #ff719d;
    }

    .anticon {
      padding: 0 10px;
    }
    input {
      display: none;
    }
  }
}
</style>
